<template>
  <!-- 技术分析 -->
  <div class="box">
    <template v-if="isHavePatent===true">
      <p class="no-patent-tip">未发现此公司的科技信息，请查看其他信息。</p>
    </template>
    <template v-else>
      <!-- 专利申请趋势 -->
      <div class="card-box">
        <el-card class="elcard" style="flex:1;align-self:normal;">
          <div slot="header" class="hd clearfix">
            <span class="tit">专利申请趋势</span>
          </div>
          <el-row>
            <el-col :span="12">
              <div style="margin:20px 30px 10px">
                <p>
                  <span style="color: #2d3a86">起止时间：</span>
                  <el-date-picker
                    v-model="chartOneStart"
                    class="el-picker"
                    type="year"
                    placeholder="开始时间"
                    @change="oneChartsDate('One')"
                  ></el-date-picker>
                  <span class="date-select-right">-</span>
                  <el-date-picker
                    v-model="chartOneEnd"
                    class="el-picker"
                    type="year"
                    placeholder="结束时间"
                    @change="oneChartsDate('One')"
                  ></el-date-picker>
                  <span class="vbtn-toggle">
                    <el-button type="primary" class="elbtn-left" :class="{'elbtn-active':tabChartActive===0}" @click="tabChartActive=0">
                      <i class="iconfont icon-zhexiantu"></i>
                    </el-button>
                    <el-button type="primary" class="elbtn-right" :class="{'elbtn-active':tabChartActive===1}" @click="tabChartActive=1">
                      <i class="iconfont icon-situation"></i>
                    </el-button>
                  </span>
                </p>
              </div>
              <div style="position:relative;width:100%;height:280px">
                <div id="chartAnalysisOne" :class="{'tab-active': tabChartActive===0}"></div>
                <div id="chartAnalysisOne2" :class="{'tab-active': tabChartActive===1}"></div>
              </div>
              
            </el-col>
            <el-col :span="12">
              <h3 style="padding:12px 0;border-bottom:1px solid #b7b6eb;">{{oneListName}}年</h3>
              <el-table
                id="table1"
                :data="oneListData"
                height="256px"
                style="width: 100%;"
                :header-cell-style="patentHeaderStyle"
                :row-class-name="tableRowClassName"
                :cell-style="patentCellStyle">
                <el-table-column
                  prop="ad"
                  width="120px"
                  label="申请日">
                </el-table-column>
                <el-table-column
                  prop="isd"
                  width="120px"
                  label="公开日">
                </el-table-column>
                <el-table-column
                  prop="title"
                  label="名称">
                </el-table-column>
                <el-table-column
                  prop="pn"
                  label="专利号">
                </el-table-column>
              </el-table>
              <el-pagination
                background
                layout="prev, pager, next"
                :total="oneTotal"
                :page-size="oneIps"
                :current-page.sync="oneCurrentPage"
                @current-change="getOneCurrentPage"
                class="el-pagination">
              </el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <!-- 发明人专利量 -->
      <div class="card-box">
        <el-card class="elcard" style="flex:1;align-self:normal;">
          <div slot="header" class="hd clearfix">
            <span class="tit">发明人专利量</span>
          </div>
          <el-row>
            <el-col :span="12">
              <div style="margin:20px 30px 10px;">
                <p>
                  <span style="color: #2d3a86">发明人：</span>
                  <el-select v-model="value1" class="el-select" @change="changeValue1" placeholder="请选择">
                    <el-option
                      v-for="item in options1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <span style="margin-left:10px;color: #2d3a86">起止时间：</span>
                  <el-date-picker
                    v-model="chartTwoStart"
                    class="el-picker2"
                    type="year"
                    placeholder="开始时间"
                    @change="oneChartsDate('Two')"
                  ></el-date-picker>
                  <span class="date-select-right">-</span>
                  <el-date-picker
                    v-model="chartTwoEnd"
                    class="el-picker2"
                    type="year"
                    placeholder="结束时间"
                    @change="oneChartsDate('Two')"
                  ></el-date-picker>
                </p>
                <div id="chartAnalysisTwo" style="width:100%;height:280px"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <h3 style="padding:12px 0;border-bottom:1px solid #b7b6eb;">发明人：<span style="color:#2f41c8">{{twoListName}}</span></h3>
              <el-table
                id="table2"
                :data="twoListData"
                height="256px"
                style="width: 100%;"
                :header-cell-style="patentHeaderStyle"
                :row-class-name="tableRowClassName"
                :cell-style="patentCellStyle">
                <el-table-column
                  prop="title"
                  label="名称">
                </el-table-column>
                <el-table-column
                  prop="pn"
                  label="专利号"
                  width="140">
                </el-table-column>
                <el-table-column
                  prop="pantentScore"
                  label="分数"
                  align="center">
                </el-table-column>
              </el-table>
              <el-pagination
                background
                layout="prev, pager, next"
                :total="twoTotal"
                :page-size="twoIps"
                :current-page.sync="twoCurrentPage"
                @current-change="getTwoCurrentPage"
                class="el-pagination">
              </el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <!-- 法律状态 -->
      <div class="card-box">
        <el-card class="elcard" style="flex:1;align-self:normal;">
          <div slot="header" class="hd clearfix">
            <span class="tit">法律状态</span>
          </div>
          <el-row>
            <el-col :span="12">
              <div id="chartAnalysisThree" style="width:100%;height:300px"></div>
            </el-col>
            <el-col :span="12">
              <h3 style="padding:12px 0;border-bottom:1px solid #b7b6eb;">法律状态：{{threeListName}}（{{percentVal}}%）</h3>
              <el-table
                id="table3"
                :data="threeListData"
                height="216px"
                style="width: 100%;"
                :row-class-name="tableRowClassName"
                :header-cell-style="patentHeaderStyle"
                :cell-style="patentCellStyle">
                <el-table-column
                  prop="title"
                  label="名称">
                </el-table-column>
                <el-table-column
                  prop="pn"
                  label="专利号"
                  width="140">
                </el-table-column>
                <el-table-column
                  prop="pantentScore"
                  label="分数"
                  align="center">
                </el-table-column>
              </el-table>
              <el-pagination
                background
                layout="prev, pager, next"
                :total="threeTotal"
                :page-size="threeIps"
                :current-page.sync="threeCurrentPage"
                @current-change="getThreeCurrentPage"
                class="el-pagination">
              </el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <!-- 机构研究领域变化 -->
      <div class="card-box">
        <el-card class="elcard" style="flex:1;align-self:normal;">
          <div slot="header" class="hd clearfix">
            <span class="tit">机构研究领域变化</span>
          </div>
          <div id="chartAnalysisFour" style="width:100%;min-height:340px"></div>
          <div v-show="!isShowChartFour" class="no-data">暂无数据</div>
        </el-card>
      </div>
    </template>
  </div>
</template>

<script>
import axios from 'axios'
import vPagination from '@/views/components/vPagination'
import Ecolors from '@/utils/chartsColors.js'
export default {
  components: {
    vPagination
  },
  data() {
    return {
      isHavePatent: null, // 是否有专利
      companyName: this.$route.query.name|| '',
      chartAnalysisData: {},
      patentHeaderStyle: function(){
        return 'font-weight: 600; color: #241c75;'
      },
      patentCellStyle: function() {
        return 'color: #7674a3'
      },
      // 专利申请趋势
      chartOneStart: '',
      chartOneEnd: '',
      chartAnalysisOne: '',
      chartAnalysisOne2: '',
      tabChartActive: 0,
      oneListName: '', // 专利申请趋势右侧list标题
      oneListData: [],
      valueChartOne: {
        appIsdObject: {
          list: [],
          types: []
        },
        appApdObject: {
          list: [],
          types: []
        }
      },
      splitDate: '',
      splitDate2: '',
      oneTotal: 0,
      oneIpi: 0, // 页码
      oneIps: 5, // 每页展示条数
      oneCurrentPage: 1,
      oneSeriesName: '', // 当前专利申请趋势 点击的点的名称
      oneFieldType: 'ad', // 默认为ad
      // 发明人专利量
      chartTwoStart: '',
      chartTwoEnd: '',
      chartAnalysisTwo: '',
      twoListName: '', // 发明人专利量右侧list标题
      twoListData: [],
      picker2: '',
      value1: '10',
      options1: [
        {
          label: 'TOP10',
          value: '10'
        },
        {
          label: 'TOP15',
          value: '15'
        },
        {
          label: 'TOP20',
          value: '20'
        },
        {
          label: 'TOP25',
          value: '25'
        },
        {
          label: 'TOP30',
          value: '30'
        },
      ],
      valueChartTwo: {
        list: [],
        types: [],
        allData: []
      },
      twoTotal: 0,
      twoIpi: 0, // 页码
      twoIps:5, // 每页展示条数
      twoCurrentPage: 1,
      // 法律状态
      threeListName: '', // 法律状态右侧list标题
      threeListData: [],
      chartAnalysisThree: '',
      valueChartThree: [],
      valueChartThreeName: [],
      percent: '', // 获取百分比
      percentVal: '', // 展示百分比
      threeTotal: 0,
      threeIpi: 0, // 页码
      threeIps: 5, // 每页展示条数
      threeCurrentPage: 1,
      // 机构研究领域变化
      chartAnalysisFour: [],
      valueChartFour: {
        legend: [],
        data: []
      },
      currentLegendName: '', // 当前选中图例
      isShowChartFour: true
    }
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2) {
            return 'warning-row';
        } 
        return '';
        
    },
    // 机构研究领域变化
    getRiverData() {
      let that = this
      function DateMange(val){
        let temp = val || 9
        let time = new Date()
        let year= time.getFullYear();  // 获取完整的年份(4位,1970)
        let month = time.getMonth()+1;  // 获取月份(0-11,0代表1月,用的时候记得加上1)
        let date = time.getDate();
        let json = {start:'',end:''}
        let preYear =  Number(year)-Number(temp)
        let preDate = date
        if(month === 2){
          let d = new Date(preYear, month, 0);
          preDate = d.getDate();
        }
        json.start = preYear+'-'+month+'-'+ preDate
        json.end = year+'-'+month+'-'+date
        return json
      } 
      /* this.$get(this.$Url.analysis.patentTrends, {
        companyName: this.companyName,
        dataType: 'patentBatch'
      }).then(data => {
        this.chartAnalysisData = data.data.patentBatch || {}
        this.renderChartAnalysisFour()
      }).catch(error => {
        console.log(error);
      }) */
      this.$post(this.$Url.analysis.queryAggs, { 
        "companyName": this.companyName,
        "musts": {
            "date_sort": "1"
        },
        "rangArr": [
            {
                "start": DateMange().start,
                "end": DateMange().end,
                "field": "ad"
            }
        ],
        "aggs": {
            "size": "10",
            "field": "ipc_kind",
            "type": "base",
            "subAggs":{
              "size": "",
                "interval": "YEAR",
                "format": "yyyy",
                "field": "ad",
                "type": "date"
            }
        }
    }).then(data => {
        if(data.data){
          this.chartAnalysisData = data.data
          this.renderChartAnalysisFour()
        }
      }).catch(error => {
        console.log(error);
      })
    },
    // 专利申请趋势
    trendsData(startYear, endYear, fieldType) {
      return this.$post(this.$Url.analysis.queryAggs, {
        companyName: this.companyName,
        musts: {
          date_sort: '1'
        },
        rangArr: [
          {
            start: `${startYear}-01-01`,
            end: `${endYear}-12-31`,
            field: fieldType
          }
        ],
        aggs: {
          size: '',
          interval: 'YEAR',
          format: 'yyyy',
          field: fieldType, // ad:申请日 isd:公开日
          type: 'date'
        }
      })
    },
    getTrendsData(startYear, endYear) {
      let tStartYear = startYear
      let tEndYear = endYear
      axios.all([this.trendsData(startYear, endYear, 'ad'), this.trendsData(startYear, endYear, 'isd')])
        .then(axios.spread((res1, res2) => {
          // 申请日数量
          let data1 = res1.data
          let list1 = []
          let types1 = []
          // 公开日数量
          let data2 = res2.data
          let list2 = []
          let types2 = []

          for(let i = tStartYear; i <= tEndYear; i++){
            list1.push(0)
            list2.push(0)
            types1.push(String(i))
            types2.push(String(i))
          }
          // 申请日数量
          for(let i in data1){
            this.$set(list1, types1.indexOf(data1[i].key_as_string), data1[i].doc_count)
          }
          this.valueChartOne.appApdObject.list = list1
          this.valueChartOne.appApdObject.types = types1
          // 公开日数量
          for(let i in data2){
            this.$set(list2, types2.indexOf(data2[i].key_as_string), data2[i].doc_count)
          }
          this.valueChartOne.appIsdObject.list = list2
          this.valueChartOne.appIsdObject.types = types2

          this.renderChartAnalysisOne()
          this.renderChartAnalysisOne2()

          let startYear = this.chartOneStart === '' ? new Date().getFullYear() - 9 : new Date(this.chartOneStart).getFullYear()
          let endYear = this.chartOneEnd === '' ? new Date().getFullYear() : new Date(this.chartOneEnd).getFullYear()
          // this.queryOneList(startYear, endYear, 'ad')
          this.queryOneList(this.oneListName, this.oneListName, 'ad')
        }))

    },
    // 专利申请趋势-折线图
    renderChartAnalysisOne() {
      this.chartAnalysisOne = this.$echarts.init(document.getElementById("chartAnalysisOne"),'macarons')
      // 专利申请趋势 起止日期、发明人专利量初始年份
      this.chartOneStart = this.chartTwoStart = this.valueChartOne.appApdObject.types[0]
      this.chartOneEnd = this.chartTwoEnd = this.valueChartOne.appApdObject.types[this.valueChartOne.appApdObject.types.length-1]
      // 默认查最早有数据的专利申请趋势
      for(let i=0;i<this.valueChartOne.appApdObject.list.length;i++){
        if(this.valueChartOne.appApdObject.list[i]>0){
          this.oneListName = this.valueChartOne.appApdObject.types[i]
          break
        }
      }
      if(this.oneListName===''){
        for(let i=0;i<this.valueChartOne.appIsdObject.list.length;i++){
          if(this.valueChartOne.appIsdObject.list[i]>0){
            this.oneListName = this.valueChartOne.appIsdObject.types[i]
            break
          }
        }
      }
      this.splitDate = (Number(this.chartOneEnd) - 1).toString() // 折线图需要虚线
      this.splitDate2 = (Number(this.chartOneEnd)).toString() // 柱状图不需要虚线
      // 实线部分，虚线部分
      let solid1=[],dotted1=[],solid2=[],dotted2=[],node1=0,node2=0
      if(this.valueChartOne.appApdObject.types.indexOf(this.splitDate)>-1){
        node1 = this.valueChartOne.appApdObject.types.indexOf(this.splitDate)
      }
      for(let i=0;i<this.valueChartOne.appApdObject.list.length;i++){
        if(i<=node1){
          solid1.push(this.valueChartOne.appApdObject.list[i])
        }else{
          solid1.push('-')
        }
        if(i>=node1){
          dotted1.push(this.valueChartOne.appApdObject.list[i])

        }else{
          dotted1.push('-')
        }
      }
      if(this.valueChartOne.appIsdObject.types.indexOf(this.splitDate)>-1){
        node2 = this.valueChartOne.appIsdObject.types.indexOf(this.splitDate)
      }
      for(let i=0;i<this.valueChartOne.appIsdObject.list.length;i++){
        if(i<=node2){
          solid2.push(this.valueChartOne.appIsdObject.list[i])
        }else{
          solid2.push('-')
        }
        if(i>=node2){
          dotted2.push(this.valueChartOne.appIsdObject.list[i])

        }else{
          dotted2.push('-')
        }
      }
      
      let optionOne = {
        tooltip: {
          confine: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
            color: "#000"
          },
          axisPointer: { type: "none" },
          formatter: function (params, ticket, callback) {
            var htmlStr = '';
            var valMap = {};
            for(var i=0;i<params.length;i++){
              var param = params[i];
              var xName = param.name;//x轴的名称
              var seriesName = param.seriesName;//图例名称
              var value = param.value;//y轴值
              var color = param.color;//图例颜色
              //过滤无效值
              if(value == '-'){
                  continue;
              }
              //过滤重叠值
              if(valMap[seriesName] == value){
                  continue;
              }
              if(i===0){
                htmlStr += xName + '<br/>';//x轴的名称
              }
              htmlStr +='<div>';
              //为了保证和原来的效果一样，这里自己实现了一个点的效果
              htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:'+color+';"></span>';
              //圆点后面显示的文本
              htmlStr += seriesName + '：' + value;
              htmlStr += '</div>';
              valMap[seriesName] = value;
            }
            return htmlStr;
          }
        },
        legend: {
          type: "scroll",
          data: ['申请日数量', '公开日数量'],
          bottom: 0,
          left: "5%",
          right: "5%"
        },
        xAxis: [
          {
            data: this.valueChartOne.appIsdObject.types,
            type: 'category',
            axisLine:{
                lineStyle:{
                color: '#e7e8ec'
                }
            },
            boundaryGap: false,
            axisLabel:{
                color: '#888797'
            },
            splitLine:{
                show:true,
                lineStyle :{
                    type: 'dashed'
                }
            },
            splitArea: {
                show: false 
            },
            axisTick:{
                show: false
            }
        },{
            type: 'category',
            axisLine:{
                lineStyle:{
                color: '#e7e8ec'
                }
            },
            axisLabel:{
                color: '#888797'
            },
            splitLine:{
                show:true,
                lineStyle :{
                    type: 'dashed'
                }
            },
            splitArea: {
                show: false 
            },
            axisTick:{
                show: true
            }
        }
        ],
        yAxis: [
            {
                type: 'value',
                axisLine:{
                    lineStyle:{
                    color: '#e7e8ec'
                    }
                },
                axisLabel:{
                    color: '#888797'
                },
                splitLine:{
                    lineStyle :{
                        type: 'dashed'
                    }
                },
                splitArea: {
                    show: false 
                },
                axisTick:{
                    show: false
                }
            },
            {
                type: 'value',
                axisLine:{
                    lineStyle:{
                    color: '#e7e8ec'
                    }
                },
                axisLabel:{
                    show:false,
                    color: '#888797'
                },
                splitLine:{
                    show:false,
                    lineStyle :{
                        type: 'dashed'
                    }
                },
                splitArea: {
                    show: false 
                },
                axisTick:{
                    show: false
                }
            }
        ],
        series: [
          {
            name: '申请日数量',
            type: "line",
            data: solid1,
            type: 'line',
            symbolSize:8,
            itemStyle:{
                normal:{
                    // 拐点上显示数值
                    label : {
                    show: false
                    },
                    borderColor:'fff',  // 拐点边框颜色
                    borderWidth: '2',
                    lineStyle:{                 
                        width:2,  // 设置线宽
                        type:'solid'  //'dotted'虚线 'solid'实线
                    }
                }
            },
            symbol:'circle',
            smooth: false
          },
          {
            name: '申请日数量', //虚线
            type: "line",
            data: dotted1,
            type: 'line',
            symbolSize:8,
            itemStyle:{
                normal:{
                    // 拐点上显示数值
                    label : {
                    show: false
                    },
                    borderColor:'fff',  // 拐点边框颜色
                    borderWidth: '2',
                    lineStyle:{                 
                        width:2,  // 设置线宽
                        type:'dotted'  //'dotted'虚线 'solid'实线
                    }
                }
            },
            symbol:'circle',
            smooth: false
          },
          {
            name: '公开日数量',
            type: "line",
            data: solid2,
            symbolSize:8,
            itemStyle:{
                normal:{
                    // 拐点上显示数值
                    label : {
                    show: false
                    },
                    borderColor:'fff',  // 拐点边框颜色
                    borderWidth: '2',
                    lineStyle:{                 
                        width:2,  // 设置线宽
                        type:'solid'  //'dotted'虚线 'solid'实线
                    }
                }
            },
            symbol:'circle',
            smooth: false,
          },
          {
            name: '公开日数量', //虚线
            type: "line",
            data: dotted2,
            smooth: true,
            type: 'line',
            symbolSize:8,
            itemStyle:{
                normal:{
                    // 拐点上显示数值
                    label : {
                    show: false
                    },
                    borderColor:'fff',  // 拐点边框颜色
                    borderWidth: '2',
                    lineStyle:{                 
                        width:2,  // 设置线宽
                        type:'dotted'  //'dotted'虚线 'solid'实线
                    }
                }
            },
            symbol:'circle',
            smooth: false,
        
          }
        ],
      }
      this.chartAnalysisOne.setOption(optionOne)
      window.addEventListener("resize", () => {
        if(this.$route.query.active === 2){
          setTimeout(() => {
            this.chartAnalysisOne.resize()
          }, 400)
        }
      })
      // 防止多次绑定click事件
      this.chartAnalysisOne.off('click')
      this.chartAnalysisOne.on('click', (params) => {
        // return
        this.oneListName = params.name
        this.oneIpi = 0
        this.oneCurrentPage = 1

        let fieldType = ''
        if(params.seriesName.indexOf('申请日')>-1){
          fieldType = 'ad'
        }else if(params.seriesName.indexOf('公开日')>-1){
          fieldType = 'isd'
        }
        this.oneFieldType = fieldType
        this.queryOneList(this.oneListName, this.oneListName, fieldType)
      })
    },
    // 
    renderChartAnalysisOne2() {
      this.chartAnalysisOne2 = this.$echarts.init(document.getElementById("chartAnalysisOne2"),'macarons')
      // 实线部分，虚线部分
      let solid1=[],dotted1=[],solid2=[],dotted2=[],node1=0,node2=0
      if(this.valueChartOne.appApdObject.types.indexOf(this.splitDate2)>-1){
        node1 = this.valueChartOne.appApdObject.types.indexOf(this.splitDate2)
      }
      for(let i=0;i<this.valueChartOne.appApdObject.list.length;i++){
        if(i<=node1){
          solid1.push(this.valueChartOne.appApdObject.list[i])
        }else{
          solid1.push('-')
        }
        if(i>=node1){
          dotted1.push(this.valueChartOne.appApdObject.list[i])

        }else{
          dotted1.push('-')
        }
      }
      if(this.valueChartOne.appIsdObject.types.indexOf(this.splitDate2)>-1){
        node2 = this.valueChartOne.appIsdObject.types.indexOf(this.splitDate2)
      }
      for(let i=0;i<this.valueChartOne.appIsdObject.list.length;i++){
        if(i<=node2){
          solid2.push(this.valueChartOne.appIsdObject.list[i])
        }else{
          solid2.push('-')
        }
        if(i>=node2){
          dotted2.push(this.valueChartOne.appIsdObject.list[i])

        }else{
          dotted2.push('-')
        }
      }
      let optionOne2 = {
        legend: {
          type: "scroll",
          data: ['申请日数量', '公开日数量'],
          bottom: 0,
          left: "5%",
          right: "5%"
        },
        tooltip: {
          confine: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
            color: "#000"
          },
          axisPointer: { type: "none" },
          formatter: function (params, ticket, callback) {
            var htmlStr = '';
            var valMap = {};
            for(var i=0;i<params.length;i++){
              var param = params[i];
              var xName = param.name;//x轴的名称
              var seriesName = param.seriesName;//图例名称
              var value = param.value;//y轴值
              var color = param.color;//图例颜色
              //过滤无效值
              if(value == '-'){
                  continue;
              }
              //过滤重叠值
              if(valMap[seriesName] == value){
                  continue;
              }
              if(i===0){
                htmlStr += xName + '<br/>';//x轴的名称
              }
              htmlStr +='<div>';
              //为了保证和原来的效果一样，这里自己实现了一个点的效果
              htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:'+color+';"></span>';
              //圆点后面显示的文本
              htmlStr += seriesName + '：' + value;
              htmlStr += '</div>';
              valMap[seriesName] = value;
            }
            return htmlStr;
          }
        },
        xAxis: [{
            data: this.valueChartOne.appIsdObject.types,
            type: 'category',
            axisLine:{
                lineStyle:{
                color: '#e7e8ec'
                }
            },
            // boundaryGap: false,
            axisLabel:{
                color: '#888797'
            },
            splitLine:{
                show:true,
                lineStyle :{
                    type: 'dashed'
                }
            },
            splitArea: {
                show: false 
            },
            axisTick:{
                show: false
            }
        },{
            type: 'category',
            axisLine:{
                lineStyle:{
                color: '#e7e8ec'
                }
            },
            axisLabel:{
                color: '#888797'
            },
            splitLine:{
                show:true,
                lineStyle :{
                    type: 'dashed'
                }
            },
            splitArea: {
                show: false 
            },
            axisTick:{
                show: true
            }
        }
    ],
        yAxis : [
            {
                type: 'value',
                axisLine:{
                    lineStyle:{
                    color: '#e7e8ec'
                    }
                },
                axisLabel:{
                    color: '#888797'
                },
                splitLine:{
                    lineStyle :{
                        type: 'dashed'
                    }
                },
                splitArea: {
                    show: false 
                },
                axisTick:{
                    show: false
                }
            },
            {
                type: 'value',
                axisLine:{
                    lineStyle:{
                    color: '#e7e8ec'
                    }
                },
                axisLabel:{
                    show:false,
                    color: '#888797'
                },
                splitLine:{
                    show:false,
                    lineStyle :{
                        type: 'dashed'
                    }
                },
                splitArea: {
                    show: false 
                },
                axisTick:{
                    show: false
                }
            }
        ],
        itemStyle: {
          barBorderRadius: [20, 20, 0, 0],
        },
        series: [
          {
            name: '申请日数量',
            type: "bar",
            data: solid1,
            barMaxWidth: 18,
            smooth: true,
            symbol: "circle",
            symbolSize: 10,
            itemStyle: {
              normal: {
                color: Ecolors.color[1]
              }
            },
            emphasis: {
              itemStyle: {
                opacity: '0.5'
              }
            }
          },
          {
            name: '公开日数量',
            type: "bar",
            data: solid2,
            barMaxWidth: 18,
            smooth: true,
            symbol: "circle",
            symbolSize: 10,
            itemStyle: {
              normal: {
                color: Ecolors.color[4]
              }
            },
            emphasis: {
              itemStyle: {
                opacity: '0.5'
              }
            },
            
          },
        ]
      }
      this.chartAnalysisOne2.setOption(optionOne2)
      window.addEventListener("resize", () => {
        if(this.$route.query.active === 2){
          setTimeout(() => {
            this.chartAnalysisOne2.resize()
          }, 400)
        }
      })
      // 防止多次绑定click事件
      this.chartAnalysisOne2.off('click')
      this.chartAnalysisOne2.on('click', (params) => {
        // return
        this.oneListName = params.name
        this.oneIpi = 0
        this.oneCurrentPage = 1

        let fieldType = ''
        if(params.seriesName.indexOf('申请日')>-1){
          fieldType = 'ad'
        }else if(params.seriesName.indexOf('公开日')>-1){
          fieldType = 'isd'
        }
        this.oneFieldType = fieldType
        this.queryOneList(this.oneListName, this.oneListName, fieldType)
      })
    },
    // picker查询专利申请趋势
    queryOne() {
      let startYear = new Date(this.chartOneStart).getFullYear()
      let endYear = new Date(this.chartOneEnd).getFullYear()
      this.fieldType = 'ad'
      this.getTrendsData(startYear, endYear)
    },
    // 查询右侧list表格
    queryOneList(startYear, endYear, fieldType) {
      this.$post(this.$Url.analysis.queryList, {
        companyName: this.companyName,
        ipi: this.oneIpi + 1,
        ips: this.oneIps,
        rang: [
          {
            field: fieldType, // ad:申请日 isd:公开日
            start: `${startYear || '2014' }-01-01`,
            end: `${endYear || '2023'}-12-31`,
          },
        ],
      }).then(data => {
        this.oneListData = data.data.result
        this.oneTotal = data.data.page.totalRow || 0
      }).catch(error => {
        console.log(error);
      })
    },
    getOneCurrentPage(val) {
      this.oneIpi = Number(val) - 1
      let startYear = new Date(this.chartOneStart).getFullYear()
      let endYear = new Date(this.chartOneEnd).getFullYear()
      this.queryOneList(this.oneListName, this.oneListName, this.oneFieldType)
    },
    // 发明人专利量
    getInventorData(startYear, endYear, size) {
      this.$post(this.$Url.analysis.queryAggs, {
        companyName: this.companyName,
        musts: {
          date_sort: '1'
        },
        rangArr: [
          {
            start: `${startYear}-01-01`,
            end: `${endYear}-12-31`,
            field: 'ad'
          }
        ],
        aggs: {
          size: (size * 2).toString(),
          showSize: Number(size),
          interval: '',
          format: '',
          field: 'inventor',
          type: 'base',
        }
      }).then(res => {
        let data = res.data
        if(data){
          // 去除不公告发明人
          for(let i in data){
            if(data[i].key.indexOf('不公告发明人')>-1){
              data.splice(i, 1)
              break
            }
          }
          let list = []
          let types = []
          for(let i in data){
            list.push(data[i].doc_count)
            types.push(data[i].key)
          }
          this.valueChartTwo.list = list
          this.valueChartTwo.types = types
          this.twoListName = this.valueChartTwo.types[0]
          this.renderChartAnalysisTwo()
          this.queryTwoList()
          this.chartAnalysisTwo.on('click', (params) => {
            this.twoListName = params.name
            this.twoIpi = 0
            this.twoCurrentPage = 1
            this.queryTwoList()
          })
        }
      }).catch(err => {})
    },
    renderChartAnalysisTwo() {
      this.chartAnalysisTwo = this.$echarts.init(document.getElementById("chartAnalysisTwo"),'macarons')
      let cTwoAllValue = [],cTwoAllData = [],cTwoAllName = [], color = Ecolors.color
      for(let i=0;i<this.valueChartTwo.types.length;i++){
        if(i>50){
          cTwoAllValue[i] = {
            value: this.valueChartTwo.list[i],
            itemStyle: {
              normal: {
                color: color[i % 51]
              }
            }
          }
        }else{
          cTwoAllValue[i] = {
            value: this.valueChartTwo.list[i],
            itemStyle: {
              normal: {
                color: color[i]
              }
            }
          }
        }
        cTwoAllName[i] = {
          type: "scatter",
          data: [],
          name: this.valueChartTwo.types[i]
        }
      }
      cTwoAllData = [
        {
          type: 'bar',
          data: cTwoAllValue
        }
      ]
      let cTwoAllDataAndName = cTwoAllData.concat(cTwoAllName)
      this.valueChartTwo.allData = cTwoAllDataAndName
      let optionTwo = {
        legend: {
          show: false,
          bottom: 0,
          data: this.valueChartTwo.types
        },
        tooltip: {
          confine: true,
          show: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
            color: "#000"
          },
          axisPointer: { type: "shadow" }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: "10%",
          containLabel: true
        },
        xAxis: [{
          data: this.valueChartTwo.types,
          type: 'category',
                axisLine:{
                    lineStyle:{
                    color: '#e7e8ec'
                    }
                },
                axisLabel:{
                    color: '#888797'
                },
                splitLine:{
                    show:true,
                    lineStyle :{
                        type: 'dashed'
                    }
                },
                splitArea: {
                    show: false 
                },
                axisTick:{
                    show: false
                }
            },{
                type: 'category',
                axisLine:{
                    lineStyle:{
                    color: '#e7e8ec'
                    }
                },
                axisLabel:{
                    color: '#888797'
                },
                splitLine:{
                    show:true,
                    lineStyle :{
                        type: 'dashed'
                    }
                },
                splitArea: {
                    show: false 
                },
                axisTick:{
                    show: true
                }
            }
        ],
        yAxis : [
                {
                    type: 'value',
                    axisLine:{
                        lineStyle:{
                        color: '#e7e8ec'
                        }
                    },
                    axisLabel:{
                        color: '#888797'
                    },
                    splitLine:{
                        lineStyle :{
                            type: 'dashed'
                        }
                    },
                    splitArea: {
                        show: false 
                    },
                    axisTick:{
                        show: false
                    }
                },
                {
                    type: 'value',
                    axisLine:{
                        lineStyle:{
                        color: '#e7e8ec'
                        }
                    },
                    axisLabel:{
                        show:false,
                        color: '#888797'
                    },
                    splitLine:{
                        show:false,
                        lineStyle :{
                            type: 'dashed'
                        }
                    },
                    splitArea: {
                        show: false 
                    },
                    axisTick:{
                        show: false
                    }
                }
            ],
        dataZoom: {
          type: 'inside'
        },
        itemStyle: {
          barBorderRadius: [20, 20, 0, 0],
        },
        barMaxWidth: '18',
        series: this.valueChartTwo.allData
      }
      this.chartAnalysisTwo.setOption(optionTwo)
      window.addEventListener("resize", () => {
        if(this.$route.query.active === 2){
          setTimeout(() => {
            this.chartAnalysisTwo.resize()
          }, 400)
        }
      })
    },
    queryTwoList() {
      let startYear = this.chartTwoStart === '' ? new Date().getFullYear() - 9 : new Date(this.chartTwoStart).getFullYear()
      let endYear = this.chartTwoEnd === '' ? new Date().getFullYear() : new Date(this.chartTwoEnd).getFullYear()
      this.$post(this.$Url.analysis.queryList, {
        companyName: this.companyName,
        ipi: this.twoIpi + 1,
        ips: this.twoIps,
        musts: {
          inventor: this.twoListName,
        },
        rang: [
          {
            field: fieldType, // ad:申请日 isd:公开日
            start: `${startYear || '2014' }-01-01`,
            end: `${endYear || '2023'}-12-31`,
          },
        ],
      }).then(data => {
        this.twoListData = data.data.result
        let that = this
        for(let i=0;i<this.twoListData.length;i++){
          let p = this.twoListData[i].pn
          this.getPatentScore(p,function(data){
            that.$set(that.twoListData[i],'pantentScore',data.data?data.data:'暂无')
          })
        }
        this.twoTotal = data.data.page.totalRow || 0
      }).catch(error => {
        console.log(error);
      })
    },
    getTwoCurrentPage(val) {
      this.twoIpi = Number(val) - 1
      this.queryTwoList()
    },
    // 发明人专利量
    queryTwo() {
      let startYear = this.chartTwoStart === '' ? new Date().getFullYear() - 9 : new Date(this.chartTwoStart).getFullYear()
      let endYear = this.chartTwoEnd === '' ? new Date().getFullYear() : new Date(this.chartTwoEnd).getFullYear()
      this.getInventorData(startYear, endYear, this.value1)
    },
    changeValue1() {
      this.queryTwo()
    },
    // 获取法律状态
    getLawData() {
      this.$post(this.$Url.analysis.queryAggs, {
        companyName: this.companyName,
        musts: {
          date_sort: '1'
        },
        aggs: {
          size: '10',
          interval: '',
          format: '',
          field: 'legal_status',
          type: 'base'
        }
      }).then(res => {
        let data = res.data
        if(data){
          for(let i in data){
            this.valueChartThreeName.push(data[i].key === '' ? '其它': data[i].key)
            this.valueChartThree.push({
              name: data[i].key === '' ? '其它': data[i].key,
              value: data[i].doc_count
            })
          }
          this.threeListName = this.valueChartThreeName[0] === '其它' ? 
            this.valueChartThreeName[1] : this.valueChartThreeName[0]
          this.renderChartAnalysisThree()
          this.queryThreeList()
          this.chartAnalysisThree.on('click', (params) => {
            let name = params.name
            if(name !== '其它'){
              this.threeListName = params.name
              this.threeIpi = 0
              this.threeCurrentPage = 1
              this.percentVal = params.percent
              this.queryThreeList()
            }
          })
        }
        
      }).catch(err => {})
    },
    renderChartAnalysisThree() {
      this.chartAnalysisThree = this.$echarts.init(document.getElementById('chartAnalysisThree'),'macarons')
      let that = this
      let optionThree = {
        tooltip : {
          trigger: 'item',
          formatter: function(x) {
            let params = x
            return `${params.data.name}：${params.data.value}(${params.percent}%)`
          }
        },
        legend: [
          {
            top:'10%',
            data: this.valueChartThreeName
          },
        ],
        series: [
          {
            type: 'pie',
            radius: ["34%", "55%"],
            center: ["50%", "65%"],
            minAngle: 20,
            avoidLabelOverlap: false,
            hoverOffset: 4,
            selectedOffset: 4,
            label: {
              normal: {
                show: true,
                formatter: function(x){
                  if(x.data.name==='授权'){
                    that.percentVal = x.percent
                  }
                  return `${x.percent}%`
                }
              },
            },
            itemStyle:{
              normal: {
                borderWidth: 3, 
                borderColor: '#fff',
              }
            },
            // roseType: "radius",
            color: Ecolors.color,
            data: this.valueChartThree
          }
        ],
      }
      this.chartAnalysisThree.setOption(optionThree)
      window.addEventListener("resize", () => {
        if(this.$route.query.active === 2){
          setTimeout(() => {
            this.chartAnalysisThree.resize()
          }, 400)
        }
      })
    },
    queryThreeList() {
      this.$post(this.$Url.analysis.queryList, {
        companyName: this.companyName,
        ipi: this.threeIpi + 1,
        ips: this.threeIps,
        musts: {
          legal_status: this.threeListName,
        },
        rang: [
          {
            field: fieldType, // ad:申请日 isd:公开日
            start: `${startYear || '2014' }-01-01`,
            end: `${endYear || '2023'}-12-31`,
          },
        ],
      }).then(data => {
        this.threeListData = data.data.result
        this.threeTotal = data.data.page.totalRow || 0
        let that = this
        for(let i=0;i<this.threeListData.length;i++){
          let p = this.threeListData[i].pn
          this.getPatentScore(p,function(data){
            that.$set(that.threeListData[i],'pantentScore',data.data?data.data:'暂无')
          })
        }
      }).catch(error => {
        console.log(error);
      })
    },
    getThreeCurrentPage(val) {
      this.threeIpi = Number(val) - 1
      this.queryThreeList()
    },
    // 机构研究领域变化
    renderChartAnalysisFour() {
      this.chartAnalysisFour = this.$echarts.init(document.getElementById('chartAnalysisFour'),'macarons')
      let rObj = this.chartAnalysisData
      let legendData = []
      let start = new Date().getFullYear()-9
      let end = start+10
      let data = []
      let x = []
      for(let i = 0 ;i<rObj.length;i++){
        let lter = rObj[i]['date_histogram#AGG'].buckets
        let name = rObj[i].key
        legendData.push(name)
        for(let o=start;o<end;o++){
          
          let num = 0
          for(let j =0;j<lter.length;j++){
            if(o == lter[j].key_as_string.substr(0,4)){
              num = lter[j].doc_count
            }
          }
          data.push([String(o),num,name])
        }
      }
      let arr = []
      for(let j=start;j<end;j++){
        x.push(j)
        for(let i=0;i<data.length;i++){
          if(data[i][0] == j){
            arr.push(data[i])
          }
        }
      }

      let optionFour = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            snap: true,
            lineStyle: {
              color: 'rgba(0,0,0,0.2)',
              width: 1,
              type: 'solid'
            }
          },
          formatter: function(x){
            let param = x
            let str = ''
            for(let i=0;i<param.length;i++){
              let paramI = param[i]
              if(paramI.data[2].length>40){
                str += `${paramI.data[2].substr(0,40)}...：${paramI.data[1]}<br/>`
              }else{
                str += `${paramI.data[2]}：${paramI.data[1]}<br/>`
              }
            }
            return str
          }
        },
        legend: {
          type: 'scroll',
          left: '5%',
          right: '5%',
          top:'5%',
          orient: 'horizontal',
          data: legendData
        },
        singleAxis: {
          top: 50,
          bottom: 50,
          axisTick: {},
          axisLabel: {
            textStyle: {
              color: "#9e9e9e"
            }
          },
          type: 'time',
          axisPointer: {
            animation: true,
            label: {
              show: true,
              color: '#9e9e9e',
              // backgroundColor: ''
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              opacity: 0.2
            }
          },
          axisLine: {
            lineStyle: {
              color: "#f0f1f3",
              width: 2
            }
          },
        },
        series: [
          {
            type: 'themeRiver',
            itemStyle: {
              emphasis: {
                shadowBlur: 8,
                shadowColor: 'rgba(0, 0, 0, 0.8)'
              }
            },
            label:{
              show: false
            },
            color: Ecolors.color,
            data: arr
          }
        ]
      }
      this.chartAnalysisFour.setOption(optionFour)
      // 图例反选
      this.chartAnalysisFour.on('legendselectchanged', (obj) => {
        const {selected, name} = obj
        if (this.currentLegendName !== name) {
          Object.keys(selected).forEach(key => {
            selected[key] = key === name ? true : false;
          });
          this.currentLegendName = name
        } else {
          if(selected[name]===false){
            Object.keys(selected).forEach(key => {
              selected[key] = true
            });
            this.currentLegendName = ''
          }
        }
        optionFour.legend.selected = selected
        this.chartAnalysisFour.setOption(optionFour)
      })

      window.addEventListener("resize", () => {
        if(this.$route.query.active === 2){
          setTimeout(() => {
            this.chartAnalysisFour.resize()
          }, 400)
        }
      })
    },
    /*
     * params: 无
     * return: 无
     * function: 时间段选择
     * */
    oneChartsDate: function(i) {
      let s = "",
        e = "";
      if (this["chart" + i + "Start"] != "") {
        s = new Date(this["chart" + i + "Start"]).getFullYear()
      }
      if (this["chart" + i + "End"] != "") {
        if (
          new Date(this["chart" + i + "End"]).getFullYear() > new Date().getFullYear()
        ) {
          this.$message({
            message: "年份不能大于当前年！",
            duration: 1500,
            center: true
          });
          this["chart" + i + "End"] = new Date();
          return
        }
        e = new Date(this["chart" + i + "End"]).getFullYear()
      }
      if (s != "" && e != "" && s >= e) {
        this.$message({
          message: "开始时间不能大于或等于结束时间！",
          duration: 1500,
          center: true
        });
        this["chart" + i + "End"] = "";
        this["chart" + i + "Start"] = "";
      }
      this["query" + i]();
    },
    
    // 获取计算分值
    getPatentScore(p,fn){
      this.$get(this.$Url.patent.patentScore,{
        pn: p
      }).then(data => fn(data)).catch(err => {
        // console.log(err);
      })
    },
    
    // 监听图表resizew
    watchChartResize() {
      this.$Bus.$on('chartResize', data => {
        if (data.active === 2||data.active === '2') {
          setTimeout(()=>{
            this.chartAnalysisOne.resize()
            this.chartAnalysisOne2.resize()
            this.chartAnalysisTwo.resize()
            this.chartAnalysisThree.resize()
            this.chartAnalysisFour.resize()
          },0)
        }
      })
    }
  },
  mounted() {
    if (this.$route.query.isHavePatent) {
      this.isHavePatent = this.$route.query.isHavePatent==='true' ? true : false
    }
    if (!this.isHavePatent) {
      let startYear = new Date().getFullYear() - 9
      let endYear = new Date().getFullYear()
      this.getTrendsData(startYear, endYear)
      this.getInventorData(startYear, endYear, '10')
      this.getLawData()
      this.getRiverData()
      // 监听图表resizew
      this.watchChartResize()
    }
  }
}
</script>

<style lang="scss" scoped>
.card-box {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.elcard {
  position: relative;
  flex: .5;
  padding: 0 !important;
  text-align: left !important;
  ::v-deep {
    .el-card__header {
      position: relative;
      &:before {
        position: absolute;
        top: 50%;
        left: 0;
        width: 5px;
        height: 30px;
        margin-top: -15px;
        content: '';
        background-color: $color101;
      }
    }
  }
  .tit {
    font-size: 14px;
    font-weight: bold;
    i {
      color: #504da6;
    }
  }
  .achievements {
    position: relative;
    li {
      display: block;
      border-bottom: 1px solid #EBEEF5;
      margin-bottom: 10px;
    }
  }
}
.box{
  min-height: calc(100vh - .7rem - 40px - .5rem - .1rem);
  text-align:left;
}
.el-row{
    background:#fff;
    margin-bottom:20px;
}
.el-table{
    padding:0 20px;
}
.elbtn-active {
  color: #fff !important;
  background-color: $mainColor !important;
}
.elbtn-active:hover, .elbtn-active:active {
  color: #fff;
  background-color: $mainColor !important;
}
.el-picker.el-input {
  width: 22% !important;
}
.el-picker2.el-input {
  width: 21% !important;
}
.vbtn-toggle{
    float:right;
    margin-right:20px;
}
#chartAnalysisOne {
  position: absolute;
  top: 0;
  left: -9999px;
  width: 100%;
  height: 280px;
}
#chartAnalysisOne2 {
  position: absolute;
  top: 0;
  left: -9999px;
  width: 100%;
  height: 280px;
}
.tab-active {
  left: 0 !important;
}
.date-select-right {
  margin: 0 4px;
}
.el-button {
  width: 48px;
  height: 40px;
  border: 0;
  color: #b8b7ee;
  background-color: #e9e9fc;
  padding: 6px;
}
.el-button:hover {
  background-color: $mainColor;
  border: 1px solid $mainColor;
  color: #fff;
}
.el-button.active {
  background-color: $mainColor;
  border: 1px solid $mainColor;
  color: #fff;
}
.elbtn-left {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.elbtn-right {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  margin-left: 2px !important;
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-select {
  width: 22%;
}
.no-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 340px;
  line-height: 340px;
  text-align: center;
}
.no-patent-tip {
  width: 100%;
  line-height: 1rem;
  padding: .1rem 0;
  font-size: .18rem;
  text-align: center;
  color: $color104;
}
</style>

